﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FrienDev.Data;
using FrienDev.SystemApps;
using System.Web.UI.WebControls;
using System.Data;

namespace FrienDev.BusinessRules
{
    public class ClubRules
    {
        public const int m_1LevelMemberTypeId = 1;//主席
        public const int m_2LevelMemberTypeId = 2;//官员
        public const int m_3LevelMemberTypeId = 3;//成员
        public const int m_4LevelMemberTypeId = 6;//待批准成员
        private static ClubRules m_instance;
        public static ClubRules Instance
        {
            get
            {
                if (m_instance == null)
                {
                    m_instance = new ClubRules();
                }
                return m_instance;
            }
        }
        public void AddClubPostPageView(int postId)
        {
            Post post = (from p in m_DataContext.Posts
                        where p.PostId == postId
                        select p).SingleOrDefault();
            if (post.Viewed == null)
            {
                post.Viewed = 1;
            }
            else
            {
                post.Viewed = post.Viewed.Value + 1;
            }
            m_DataContext.SubmitChanges();
        }
        private FrienDevDataContext m_DataContext = FrienDevDataContext.Instance;
        /// <summary>
        /// 取得俱乐部最新15个Post
        /// </summary>
        /// <returns></returns>
        public List<Post> GetCurrentUserClubTopics(int clubId)
        {
            IEnumerable<Post> posts = from p in m_DataContext.Posts
                                      where p.PostId == p.ParentId && p.ObjectType == 0 && p.ObjectId == clubId
                                      orderby p.IsTop descending, p.CreateDateTime descending
                                      select p;
            //var topics = from tp in m_DataContext.Posts
            //             where tp.ObjectId == clubId && tp.ObjectType == 0
            //             orderby tp.CreateDateTime 
            //             group tp by tp.ParentId into g
            //             select g;
            
            
            return posts.Take<Post>(15).ToList<Post>();
        }

        /// <summary>
        /// 取得俱乐部Post（分页）的数量
        /// </summary>
        /// <param name="clubId"></param>
        /// <returns></returns>
        public int GetPagingCurrentUserClubTopicsCount(int clubId)
        {
            IEnumerable<Post> posts = from p in m_DataContext.Posts
                                      where p.PostId == p.ParentId && p.ObjectType == 0 && p.ObjectId == clubId
                                      orderby p.IsTop descending, p.CreateDateTime descending
                                      select p;
            return posts.Count();
        }
        /// <summary>
        /// 取得俱乐部Post（分页）
        /// </summary>
        /// <param name="clubId"></param>
        /// <returns></returns>
        public List<Post> GetPagingCurrentUserClubTopics(int clubId, int beginId, int pageSize)
        {
            IEnumerable<Post> posts = (from p in m_DataContext.Posts
                                      where p.PostId == p.ParentId && p.ObjectType == 0 && p.ObjectId == clubId
                                      orderby p.IsTop descending,p.CreateDateTime descending
                                      select p).Skip(beginId).Take(pageSize);
            return posts.ToList<Post>();
        }

        public void TopClubPost(string postId)
        {
            int curPostId = int.Parse(postId);
            Post curPost = GetPostObjectByPostId(curPostId);
            curPost.IsTop = !(curPost.IsTop);
            m_DataContext.SubmitChanges();
        }

        public bool IsClubMemberByClubId(int clubId)
        {
            string curUId = UserRules.Instance.GetCurrentUserId();
            IEnumerable<ClubMember> info = from uc in m_DataContext.ClubMembers
                                           where uc.UserId == curUId && uc.ClubId == clubId && uc.ClubMemberTypeId<=m_3LevelMemberTypeId
                                           select uc;
            if (info.Count() > 0)
            {
                return true;
            }
            return false;
            
 
        }
        public IEnumerable<ClubMember> GetCurrentUserInfo(int clubId)
        {
            string curUId=UserRules.Instance.GetCurrentUserId();
            IEnumerable<ClubMember> info = from uc in m_DataContext.ClubMembers
                       where uc.UserId == curUId && uc.ClubId == clubId
                       select uc;
            return info;
        }

        /// <summary>
        /// 是否是club官员或主席
        /// </summary>
        /// <param name="clubId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool GetIsAdminOfClubByUserIdAndClubId(int clubId, string userId)
        {
            int flag = 0;
            IEnumerable<ClubMember> cMember = from cm in m_DataContext.ClubMembers
                                  where cm.ClubId == clubId && cm.ClubMemberTypeId <m_3LevelMemberTypeId
                                  select cm;
            foreach (ClubMember cmone in cMember)
            {
                if (cmone.UserId == userId)
                {
                    flag++;
                }
           
            }
            if (flag > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 删除消息
        /// </summary>
        /// <param name="messageId"></param>
        public void DeletePostByPostId(string postId)
        {
            int currentpostId = int.Parse(postId);
            Post curMsg = GetPostObjectByPostId(currentpostId);
            m_DataContext.Posts.DeleteOnSubmit(curMsg);
            m_DataContext.SubmitChanges();

        }

        /// <summary>
        /// 取得话题主题对象
        /// </summary>
        /// <param name="messageId"></param>
        /// <returns></returns>
        public Post GetPostObjectByPostId(int postId)
        {
            IEnumerable<Post> currentPost = from c in m_DataContext.Posts
                                              where c.PostId == postId
                                              select c;
            if (currentPost.Count<Post>() > 0)
            {
                return currentPost.First<Post>();
            }
            else
                return null;
        }

        /// <summary>
        /// 删除主题
        /// </summary>
        /// <param name="messageId"></param>
        public void DeleteSessionPostByPostId(string postId)
        {
            int curPostId = int.Parse(postId);
            Post post = GetPostObjectByPostId(curPostId);
            IEnumerable<Post> currentPost = (from c in m_DataContext.Posts
                                             where c.PostId == curPostId
                                               select c).Union(
                                              from d in m_DataContext.Posts
                                              where d.ParentId == post.ParentId
                                              select d);
            if (currentPost.Count<Post>() == 1)
            {
                DeletePostByPostId(currentPost.ElementAt<Post>(0).PostId.ToString());
                return;
            }
            for (int i = currentPost.Count<Post>() - 1; i > 0; i--)
            {
                DeletePostByPostId(currentPost.ElementAt<Post>(i).PostId.ToString());
            }
            

        }
        
        /// <summary>
        /// 取得俱乐部Post
        /// </summary>
        /// <returns></returns>
        public object GetCurrentUserClubPagingTopics()
        {
            int clubId;
            var cId = from cu in m_DataContext.ClubMembers
                      where cu.UserId == UserRules.Instance.GetCurrentUserId()
                      select cu;
            if (cId.Count() > 0)
            {
                clubId = Convert.ToInt32(cId.First().ClubId);
            }
            else
            {
                clubId = 0;
            }
            var topics = from tp in m_DataContext.Posts
                         where tp.UserId == UserRules.Instance.GetCurrentUserId() && tp.ObjectId == clubId && tp.ObjectType == 0
                         orderby tp.CreateDateTime descending
                         group tp by tp.ParentId into g
                         select new
                         {
                             replyCount = g.Count(),
                             topicPosts = g,
                             replyCountAndViewed=GetClubReplyCountAndViewed(g.Count(),g.Last().Viewed.Value),
                             lastPost = g.First(),
                             topPost = g.Last(),
                             postTitle = g.Last().Title,
                             postUrl=GetClubPostUrl(g.Last().PostId,g.Last().ObjectId),
                             shortDate = GetShortDate(g.Last().CreateDateTime),
                             author = g.Last().User.FullName,
                             authorId = g.Last().UserId,
                             authorUrl = ApiHelper.Instance.GetUserHomepageLink(g.Last().UserId),
                             lastReplyTitle = g.First().Title,
                             lastReplyUrl = GetClubPostUrl(g.First().PostId, g.Last().ObjectId),
                             lastReplyDateTime = GetLongDateTime(g.First().CreateDateTime),
                             lastReplyAuthor = g.First().User.FullName,
                             lastReplyAuthorId = g.First().UserId,
                             lastReplyAuthorUrl = ApiHelper.Instance.GetUserHomepageLink(g.First().UserId)
                         };
            return topics;
        }

        public IEnumerable<Post> GetReplyPosts(int postId)
        {
            var temp = from tp in m_DataContext.Posts
                       where tp.ParentId == postId
                       orderby tp.CreateDateTime descending
                       select tp;
            return temp;
        }
        public string GetClubReplyCountAndViewed(int postId, int viewed)
        {
            int replyCount = GetReplyPosts(postId).Count() - 1;
            return replyCount.ToString() + "/" + viewed.ToString();
        }


        public string GetClubPostUrl(int parentId,int clubId)
        {
            return "/club/PostDetail.aspx?parentId=" + parentId.ToString()+"&clubId="+clubId.ToString();
        }

        public string GetShortDate(DateTime dt)
        {
            return dt.ToString("MM-dd");
        }

        public string GetLongDateTime(DateTime dt)
        {
            return dt.ToString("MM-dd HH:mm");
        }

        /// <summary>
        /// 取得俱乐部Logo的Url
        /// </summary>
        /// <param name="clubId">俱乐部Id</param>
        /// <returns>俱乐部Logo的Url字符串</returns>
        public string GetClubLogoUrl(string clubId)
        {
            IEnumerable<string> lfname = from cl in m_DataContext.Clubs
                            where cl.ClubId == int.Parse(clubId)
                            select cl.LogoFileName;
            string clfname = "~/Upload/Club/" + lfname.SingleOrDefault();
            return clfname;
        }

        /// <summary>
        /// 取得俱乐部邀请页面链接
        /// </summary>
        /// <returns></returns>
        public string GetClubInvitePageUrl(string clubId)
        {
            return "~/Club/Invite.aspx?clubId="+clubId;
        }

        #region by cciel
        private ClubRules()
        {
        }

        public DataTable GetClubTypes()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("texts", typeof(String)));
            dt.Columns.Add(new DataColumn("values", typeof(String)));
            dt.Rows.Add(".net俱乐部", "0");
            dt.Rows.Add("IT技术俱乐部", "3");
            dt.Rows.Add("学生俱乐部", "1");
            dt.Rows.Add("兴趣爱好", "2");
            return dt;
        }

        public string GetNameByMemberTypeId(int memberTypeId)
        {
            switch(memberTypeId)
            {
                case 1:
                return "主席";
                case 2:
                return "官员";
                case 3:
                return "成员";
                case 6:
                return "待批准成员";
            }
            return "";
        }

        //by cciel
        public int AddClub(int cityId, string clubName, string description, string logoFile, bool addRule, bool privacy, int clubType)
        {
            Club club = new Club();
            club.CityId = cityId;
            club.ClubName = clubName;
            club.Description = description;
            club.LogoFileName = logoFile;
            club.AddRule = addRule;
            club.PrivacyType = privacy;
            club.ClubType = clubType;
            club.CreateDate = DateTime.Now;
            m_DataContext.Clubs.InsertOnSubmit(club);
            m_DataContext.SubmitChanges();
            return club.ClubId;
        }

        //by cciel
        public void AddClubMember(int clubId, string userId, DateTime joinDate, int memberTypeId)
        {
            ClubMember cm = new ClubMember();
            cm.ClubId = clubId;
            cm.UserId = userId;
            cm.JoinDateTime = joinDate;
            cm.ClubMemberTypeId = memberTypeId;
            cm.VisitTimes = 0;

            m_DataContext.ClubMembers.InsertOnSubmit(cm);
            
            m_DataContext.SubmitChanges();
            //FIX ME:如果重构，需要把下面的添加Track的方法提出来
            if (memberTypeId <= m_3LevelMemberTypeId)
            {
                ApiHelper.Instance.AppendTodayTrack(userId, typeof(ClubApplication), 0, new string[] { clubId.ToString(), cm.Club.ClubName });
            }
            
        }

        //by cciel
        public Club GetClubByClubId(int clubId)
        {
            if (clubId == -1)
            {
                return null;
            }
            return (from club in m_DataContext.Clubs
                    where club.ClubId == clubId
                    select club).SingleOrDefault();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="clubId"></param>
        /// <returns>true为公开</returns>
        public bool GetClubIsOpenByClubId(int clubId)
        {
            if (clubId == -1)
            {
                return true;
            }
            return (from club in m_DataContext.Clubs
                    where club.ClubId == clubId
                    select club).SingleOrDefault().PrivacyType;
        }

        public int GetClubMemberAmountByClubId(int clubId)
        {
            return (from cms in m_DataContext.ClubMembers
                    where cms.ClubId == clubId
                    select cms).Count();
        }

        /// <summary>
        /// 获得我的俱乐部数量
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetClubListCountByUserId(string userId)
        {
            IEnumerable<ClubMember> clubs = from cm in m_DataContext.ClubMembers
                                      where cm.UserId == userId && cm.ClubMemberTypeId <= m_3LevelMemberTypeId
                                      //join c in m_DataContext.Clubs on cm.ClubId equals c.ClubId
                                      //orderby cm.JoinDateTime descending
                                      select cm;
            return clubs.Count();

        }
        /// <summary>
        /// 获得我的俱乐部列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IEnumerable<ClubMember> GetClubListByUserId(string userId, int pageIndex, int pageSize)
        {
            IEnumerable<ClubMember> clubs = (from cm in m_DataContext.ClubMembers
                                       where cm.UserId == userId && cm.ClubMemberTypeId <= m_3LevelMemberTypeId
                                       //join c in m_DataContext.Clubs on cm.ClubId equals c.ClubId
                                       orderby cm.Club.CreateDate descending
                                       select cm).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return clubs;

        }

        public int GetFriendClubListCountByUserIdAndType(string userId, int type)
        {
            IEnumerable<Club> clubs = (from cm in m_DataContext.ClubMembers
                                       where (from f in m_DataContext.Friends
                                              where f.UserId == userId && f.IsAccepted == true
                                              select f.FriendId).Contains(cm.UserId) && cm.ClubMemberTypeId <= m_3LevelMemberTypeId
                                       join c in m_DataContext.Clubs on cm.ClubId equals c.ClubId
                                       where c.ClubType == type
                                       //orderby cm.JoinDateTime descending
                                       select c).Distinct();
            return clubs.Count();

        }
        public object GetFriendClubListByUserIdAndType(string userId, int type, int pageIndex, int pageSize)
        {
            IEnumerable<Club> clubs = (from cm in m_DataContext.ClubMembers
                                       where (from f in m_DataContext.Friends
                                              where f.UserId == userId && f.IsAccepted == true
                                              select f.FriendId).Contains(cm.UserId) && cm.ClubMemberTypeId <= m_3LevelMemberTypeId
                                       join c in m_DataContext.Clubs on cm.ClubId equals c.ClubId
                                       where c.ClubType == type
                                       orderby c.CreateDate descending
                                       select c).Distinct().Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return clubs;

        }

        /// <summary>
        /// 获得我的俱乐部数量（根据类型）
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public int GetClubListCountByUserIdAndType(string userid, int type)
        {
            IEnumerable<ClubMember> clubs = from cm in m_DataContext.ClubMembers
                                      where cm.UserId == userid && cm.ClubMemberTypeId <= m_3LevelMemberTypeId
                                      //join c in m_DataContext.Clubs on cm.ClubId equals c.ClubId
                                      where cm.Club.ClubType == type
                                      //orderby cm.JoinDateTime descending
                                      select cm;
            return clubs.Count();
        }

        /// <summary>
        /// 获得我的俱乐部列表（根据类型）
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="type"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IEnumerable<ClubMember> GetClubListByUserIdAndType(string userid, int type, int pageIndex, int pageSize)
        {
            IEnumerable<ClubMember> clubs = (from cm in m_DataContext.ClubMembers
                                       where cm.UserId == userid && cm.ClubMemberTypeId <= m_3LevelMemberTypeId
                                       //join c in m_DataContext.Clubs on cm.ClubId equals c.ClubId
                                       where cm.Club.ClubType == type
                                       orderby cm.Club.CreateDate descending
                                       select cm).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return clubs;
        }

        public IEnumerable<Club> GetOwnClubByUserId(string userId)
        {
            IEnumerable<Club> clubs = from cm in m_DataContext.ClubMembers
                                      where cm.UserId == userId && (cm.ClubMemberTypeId == m_1LevelMemberTypeId || cm.ClubMemberTypeId == m_2LevelMemberTypeId)
                                      join c in m_DataContext.Clubs on cm.ClubId equals c.ClubId
                                      orderby cm.JoinDateTime descending
                                      select c;
            return clubs;
        }
        public string GetClubHeadByClubId(int clubId)
        {
            return (from cm in m_DataContext.ClubMembers
                    where cm.ClubId == clubId && cm.ClubMemberTypeId == m_1LevelMemberTypeId
                    select cm).SingleOrDefault().User.FullName;
        }

        public void UpdateClubInfoByClubId(int clubId, int cityId, string clubName, string description, string logoFile, bool addRule, bool privacy, int clubType)
        {
            Club club = (from c in m_DataContext.Clubs
                         where c.ClubId == clubId
                         select c).SingleOrDefault();
            club.City = UserRules.Instance.GetCityByCityId(cityId);
            club.ClubName = clubName;
            club.Description = description;
            if (logoFile != "")
            {
                club.LogoFileName = logoFile;
            }
            club.AddRule = addRule;
            club.PrivacyType = privacy;
            club.ClubType = clubType;
            m_DataContext.SubmitChanges();
        }
        /// <summary>
        /// 获得好友俱乐部数量
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int GetFriendClubListCountByUserId(string userId)
        {
            IEnumerable<Club> clubs = (from cm in m_DataContext.ClubMembers
                                       where (from f in m_DataContext.Friends
                                              where f.UserId == userId && f.IsAccepted == true
                                              select f.FriendId).Contains(cm.UserId) && cm.ClubMemberTypeId <= m_3LevelMemberTypeId
                                       //join c in m_DataContext.Clubs on cm.ClubId equals c.ClubId
                                       //orderby cm.JoinDateTime descending
                                       select cm.Club).Distinct();
            return clubs.Count();

        }
        /// <summary>
        /// 获得好友的俱乐部列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IEnumerable<Club> GetFriendClubListByUserId(string userId, int pageIndex, int pageSize)
        {
            IEnumerable<Club> clubs = (from cm in m_DataContext.ClubMembers
                                       where (from f in m_DataContext.Friends
                                              where f.UserId == userId && f.IsAccepted == true
                                              select f.FriendId).Contains(cm.UserId) && cm.ClubMemberTypeId <= m_3LevelMemberTypeId
                                       //join c in m_DataContext.Clubs on cm.ClubId equals c.ClubId
                                       orderby cm.Club.CreateDate descending
                                       select cm.Club).Distinct().Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return clubs;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="clubId"></param>
        /// <param name="amount">获取个数,-1为所有</param>
        /// <returns></returns>
        public IEnumerable<User> GetRecentVisitorListByClubId(int clubId, int amount)
        {
            IEnumerable<User> visitors = from visit in m_DataContext.ClubVisitors
                                         where visit.ClubId == clubId
                                         orderby visit.LastVisitDateTime descending
                                         join user in m_DataContext.Users on visit.VisitorId equals user.UserId
                                         select user;
            if (amount != -1)
            {
                return visitors.Take(amount);//最近访问的人
            }
            return visitors;
        }

        public IEnumerable<User> GetMemberListByClubId(int clubId, int amount)
        {
            IEnumerable<User> visitors = from visit in m_DataContext.ClubMembers
                                         where visit.ClubId == clubId && visit.ClubMemberTypeId <= m_3LevelMemberTypeId
                                         orderby visit.JoinDateTime descending
                                         join user in m_DataContext.Users on visit.UserId equals user.UserId
                                         select user;
            if (amount != -1)
            {
                return visitors.Take(amount);
            }
            return visitors;
        }

        public IEnumerable<User> GetToBeMemberListByClubId(int clubId, int amount)
        {
            IEnumerable<User> visitors = from visit in m_DataContext.ClubMembers
                                         where visit.ClubId == clubId && visit.ClubMemberTypeId == m_4LevelMemberTypeId
                                         orderby visit.JoinDateTime descending
                                         join user in m_DataContext.Users on visit.UserId equals user.UserId
                                         select user;
            if (amount != -1)
            {
                return visitors.Take(amount);
            }
            return visitors;
        }

        public void AddVisitor(string userId,int clubId)
        {
            ClubVisitor visitor = (from v in m_DataContext.ClubVisitors
                                   where v.VisitorId == userId && v.ClubId == clubId
                               select v).SingleOrDefault();
            if (visitor != null)
            {
                visitor.LastVisitDateTime = DateTime.Now;
            }
            else
            {
                visitor = new ClubVisitor
                {
                    VisitorId = userId,
                    ClubId = clubId,
                    LastVisitDateTime = DateTime.Now
                };
                m_DataContext.ClubVisitors.InsertOnSubmit(visitor);
            }
            m_DataContext.SubmitChanges();
            IEnumerable<ClubVisitor> visitors = from v in m_DataContext.ClubVisitors
                                            where v.ClubId == clubId
                                            orderby v.LastVisitDateTime descending
                                            select v;
            if (visitors.Count() > 20)
            {
                m_DataContext.ClubVisitors.DeleteOnSubmit(visitors.First());
                m_DataContext.SubmitChanges();
            }
        }
        /// <summary>
        /// 搜索俱乐部
        /// </summary>
        /// <param name="key"></param>
        /// <param name="type"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<Club> SearchClubByKeyAndType(string key, int type, int pageIndex, int pageSize)
        {
            if (type != -1)
            {
                return (from c in m_DataContext.Clubs
                        where c.ClubName.Contains(key) && c.ClubType == type
                        orderby c.CreateDate descending, c.ClubMembers.Count descending
                        select c).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                return (from c in m_DataContext.Clubs
                       where c.ClubName.Contains(key)
                        orderby c.CreateDate descending, c.ClubMembers.Count descending
                        select c).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
        }
        /// <summary>
        /// 获得搜索俱乐部结果的数量
        /// </summary>
        /// <param name="key"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public int GetSearchClubCountByKeyAndType(string key, int type)
        {
            if (type != -1)
            {
                return (from c in m_DataContext.Clubs
                        where c.ClubName.Contains(key) && c.ClubType == type
                        //orderby c.ClubMembers.Count descending
                        select c).Count();
            }
            else
            {
                return (from c in m_DataContext.Clubs
                        where c.ClubName.Contains(key)
                        //orderby c.ClubMembers.Count descending
                        select c).Count();
            }
        }
        /// <summary>
        /// 根据城市和类型搜索俱乐部
        /// </summary>
        /// <param name="key"></param>
        /// <param name="type"></param>
        /// <param name="city"></param>
        /// <returns></returns>
        public List<Club> SearchClubByKeyAndTypeAndCity(string key, int type, int city, int pageIndex, int pageSize)
        {
            if (type != -1)
            {
                return (from c in m_DataContext.Clubs
                        where c.ClubName.Contains(key) && c.ClubType == type && c.CityId == city
                        orderby c.CreateDate descending, c.ClubMembers.Count descending
                        select c).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                return (from c in m_DataContext.Clubs
                        where c.ClubName.Contains(key) && c.CityId == city
                        orderby c.CreateDate descending, c.ClubMembers.Count descending
                        select c).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
        }
        /// <summary>
        /// 获得搜索俱乐部结果的数量
        /// </summary>
        /// <param name="key"></param>
        /// <param name="type"></param>
        /// <param name="city"></param>
        /// <returns></returns>
        public int GetSearchClubCountByKeyAndTypeAndCity(string key, int type, int city)
        {
            if (type != -1)
            {
                return (from c in m_DataContext.Clubs
                        where c.ClubName.Contains(key) && c.ClubType == type && c.CityId == city
                        //orderby c.ClubMembers.Count descending
                        select c).Count();
            }
            else
            {
                return (from c in m_DataContext.Clubs
                        where c.ClubName.Contains(key) && c.CityId == city
                        //orderby c.ClubMembers.Count descending
                        select c).Count();
            }
        }



        public string GetRoleByClubIdAndUserId(int clubid, string userid)
        {
            return GetNameByMemberTypeId((from cm in m_DataContext.ClubMembers
                       where cm.ClubId == clubid && cm.UserId == userid
                       select cm).SingleOrDefault().ClubMemberTypeId);
        }

        /// <summary>
        /// 是否是club主席
        /// </summary>
        /// <param name="clubId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool GetIsHeadOfClubByUserIdAndClubId(int clubId, string userId)
        {
            ClubMember cMember = (from cm in m_DataContext.ClubMembers
                         where cm.ClubId == clubId && cm.ClubMemberTypeId == m_1LevelMemberTypeId
                         select cm).SingleOrDefault();
            if (cMember.UserId == userId)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 是否是club普通会员
        /// </summary>
        /// <param name="clubId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool GetIsNormalMemberByUserIdAndClubId(int clubId, string userId)
        {
            IEnumerable<ClubMember> info = from uc in m_DataContext.ClubMembers
                                           where uc.UserId == userId && uc.ClubId == clubId && uc.ClubMemberTypeId == m_3LevelMemberTypeId
                                           select uc;
            if (info.Count() > 0)
            {
                return true;
            }
            return false;
        }

        public int GetMemberTypeIdByUserIdAndClubId(int clubId, string userId)
        {
            ClubMember cm = (from uc in m_DataContext.ClubMembers
                                           where uc.UserId == userId && uc.ClubId == clubId
                                           select uc).SingleOrDefault();
            
            if (cm != null)
            {
                return cm.ClubMemberTypeId;
            }
            else
            {
                return -1;
            }
            //if (info.Count() > 0)
            //{
            //    return true;
            //}
            //return false;
        }

        public void PermitClubMemberByUserIdAndClubId(string[] userId, int clubId)
        {
            for (int i = 0; i < userId.Length; i++)
            {
                ClubMember cMember = (from cm in m_DataContext.ClubMembers
                                      where cm.ClubId == clubId && cm.UserId == userId[i]
                                      select cm).SingleOrDefault();
                cMember.ClubMemberTypeId = m_3LevelMemberTypeId;
                ApiHelper.Instance.AppendTodayTrack(userId[i], typeof(ClubApplication), 0, new string[] { clubId.ToString(), cMember.Club.ClubName });
            }
            m_DataContext.SubmitChanges();
            //FIX ME:如果重构，需要把下面的添加Track的方法提出来
            
        }

        public void UpgradeClubMemberByUserIdAndClubId(string[] userId, int clubId)
        {
            for (int i = 0; i < userId.Length; i++)
            {
                ClubMember cMember = (from cm in m_DataContext.ClubMembers
                                      where cm.ClubId == clubId && cm.UserId == userId[i]
                                      select cm).SingleOrDefault();
                if (cMember.ClubMemberTypeId == m_3LevelMemberTypeId)
                {
                    cMember.ClubMemberTypeId = m_2LevelMemberTypeId;
                }
            }
            m_DataContext.SubmitChanges();

        }

        public void DegradeClubMemberByUserIdAndClubId(string[] userId, int clubId)
        {
            for (int i = 0; i < userId.Length; i++)
            {
                ClubMember cMember = (from cm in m_DataContext.ClubMembers
                                      where cm.ClubId == clubId && cm.UserId == userId[i]
                                      select cm).SingleOrDefault();
                if (cMember.ClubMemberTypeId == m_2LevelMemberTypeId)
                {
                    cMember.ClubMemberTypeId = m_3LevelMemberTypeId;
                }
            }
            m_DataContext.SubmitChanges();

        }

        public void KickOutMemberByUserIdAndClubId(string[] userId, int clubId)
        {
            for (int i = 0; i < userId.Length; i++)
            {
                ClubMember cMember = (from cm in m_DataContext.ClubMembers
                                      where cm.ClubId == clubId && cm.UserId == userId[i]
                                      select cm).SingleOrDefault();
                if (cMember.ClubMemberTypeId == m_2LevelMemberTypeId || cMember.ClubMemberTypeId == m_3LevelMemberTypeId)
                {
                    m_DataContext.ClubMembers.DeleteOnSubmit(cMember);
                }
            }
            m_DataContext.SubmitChanges();
        }

        public void QuitClubByUserIdAndClubId(string userId, int clubId)
        {
            ClubMember cMember = (from cm in m_DataContext.ClubMembers
                                  where cm.ClubId == clubId && cm.UserId == userId
                                  select cm).SingleOrDefault();
            m_DataContext.ClubMembers.DeleteOnSubmit(cMember);
            m_DataContext.SubmitChanges();
        }
        #endregion

        /// <summary>
        /// 获得发表话题留言板的主题
        /// </summary>
        /// <param name="m_ClubId"></param>
        /// <returns></returns>
        public IEnumerable<Post> GetClubTopicMessage(int clubId)
        {
            IEnumerable<Post> posts = from p in m_DataContext.Posts
                                      where p.PostId == p.ParentId && p.ObjectType == 0 && p.ObjectId == clubId
                                      orderby p.CreateDateTime descending
                                      select p;
            return posts;
        }

        /// <summary>
        /// 获得单一话题组
        /// </summary>
        /// <param name="clubId"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public IEnumerable<Post> GetClubPostGroupsByParentId(int clubId, int parentId)
        {
            IEnumerable<Post> posts = from p in m_DataContext.Posts
                                      where p.ParentId == parentId && p.ObjectType == 0 && p.ObjectId == clubId
                                      orderby p.CreateDateTime 
                                      select p;
            return posts; 
        }

        /// <summary>
        /// 获得单一话题组数量
        /// </summary>
        /// <param name="clubId"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public int GetClubPostGroupsByParentIdCount(int clubId, int parentId)
        {
            IEnumerable<Post> posts = from p in m_DataContext.Posts
                                      where p.ParentId == parentId && p.ObjectType == 0 && p.ObjectId == clubId
                                      orderby p.CreateDateTime 
                                      select p;
            return posts.Count();
        }

        public void DeleteClubPostByPostId(int postId)
        {
            IEnumerable<Post> post = from p in m_DataContext.Posts
                                     where p.PostId == postId 
                                     select p;
            m_DataContext.Posts.DeleteOnSubmit(post.SingleOrDefault());
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 删除俱乐部的某条留言及其所有回复
        /// </summary>
        /// <param name="activityid"></param>
        /// <param name="parentid"></param>
        public void DeleteClubTopicMessageAndReplys(int clubId, int parentId)
        {
            IEnumerable<Post> posts = from p in m_DataContext.Posts
                                      where p.ParentId == parentId && p.ObjectType == 0 && p.ObjectId == clubId
                                      select p;
            foreach (var post in posts)
            {
                m_DataContext.Posts.DeleteOnSubmit(post);
            }
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 向俱乐部的某条留言添加回复
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="content"></param>
        /// <param name="activityid"></param>
        /// <param name="parentId"></param>
        public void ReplyMessage(string userId, string content, int clubId, int parentId)
        {
            Post post = new Post
            {
                UserId = userId,
                ParentId = parentId,
                Content = content,
                CreateDateTime = DateTime.Now,
                IsTop = false,
                ObjectType = 0,
                ObjectId = clubId
            };
            m_DataContext.Posts.InsertOnSubmit(post);
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 取出俱乐部留言的所有回复ByParentId
        /// </summary>
        /// <param name="activityid"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        public IEnumerable<Post> GetClubReplyMessageByParentId(int clubId, int parentId)
        {
            IEnumerable<Post> posts = from p in m_DataContext.Posts
                                      where p.ParentId == parentId && p.ObjectType == 0 && p.ObjectId == clubId & p.PostId != p.ParentId
                                      orderby p.CreateDateTime ascending
                                      select p;
            return posts;
        }

        /// <summary>
        /// 向活动添加新的留言主题
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="content"></param>
        public Post SendMessage(string userId, string title,string content, int activityid)
        {
            Post post = new Post
            {
                UserId = userId,
                Content = content,
                CreateDateTime = DateTime.Now,
                IsTop = false,
                ObjectType = 0,
                ObjectId = activityid,
                Title=title,
                Viewed=1
            };
            m_DataContext.Posts.InsertOnSubmit(post);
            m_DataContext.SubmitChanges();
            post.ParentId = post.PostId;
            m_DataContext.SubmitChanges();
            return post;
        }

    }
}
